import { Injectable } from '@nestjs/common';
import { LoggerService } from 'src/modules/logger/logger.service';

@Injectable()
export class CommonService {
  constructor(private readonly loggerService: LoggerService) {}
  async retryWithRequest(
    requestCallback: () => Promise<any>,
    retryCount: number = 5,
    delay: number = 2000,
  ) {
    let retry = 0;
    while (retry < retryCount) {
      try {
        return await requestCallback();
      } catch (error) {
        this.loggerService.logHttpRequestError(error.message, error.url, error.code);
        retry++;
        if (retry >= retryCount) {
          console.log('请求失败', error);
          throw error;
        }
        await new Promise((resolve) => setTimeout(resolve, delay));
        return this.retryWithRequest(requestCallback, retryCount, delay);
      }
    }
  }
}
